﻿var dateFormat = "dd/mm/yyyy";
var warningColor = "#FFE4C4";
var normalColor = "";

function checkRequiredInputs(requiredInputs) {
	
    // Example: var requiredInputs = [['name','name_required'],['code','code_required'],['description','description_required'],['object_type','object_type_required'],['object_id','object_id_required'],['status','status_required'],['notification','notification_required']];
	
	var valid = true;

	for ( var i = 0; i < requiredInputs.length; i++) 
	{
		var pair = requiredInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		if (input.length && lbl.length)// P.V.Van modified
		{
			if (input.val().trim() != '') {
				input.css("background-color", normalColor);
				lbl.css("display","none");
				
			} else {
				input.css("background-color", warningColor);		
				lbl.css("display","block");
				valid = false;
				var invalidError =  $('#' + pair[0] + "_invalid");
				if (invalidError.length > 0)
				{
					invalidError.css("display", "none");
				}
			}
		}
	}

	return valid;
}

function checkRequiredIsGroupInputs(requiredIsGroupInputs,idCheckBox) {
	
    // Example: var requiredInputs = [['name','name_required'],['code','code_required'],['description','description_required'],['object_type','object_type_required'],['object_id','object_id_required'],['status','status_required'],['notification','notification_required']];
	if(document.getElementById(idCheckBox).checked==true)
		return true;
	var valid = true;

	for ( var i = 0; i < requiredIsGroupInputs.length; i++) 
	{
		var pair = requiredIsGroupInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		if (input.length && lbl.length)
		{
			if (input.val().trim() != '') {
				input.css("background-color", normalColor);
				lbl.css("display","none");
				
			} else {
				input.css("background-color", warningColor);		
				lbl.css("display","block");
				valid = false;
			}
		}
	}

	return valid;
}

function checkRequiredInQuotationInputs(requiredInQuotationInputs,idCheckBox) {
	
    // Example: var requiredInputs = [['name','name_required'],['code','code_required'],['description','description_required'],['object_type','object_type_required'],['object_id','object_id_required'],['status','status_required'],['notification','notification_required']];
	var notCheck= false;
	if(document.getElementById(idCheckBox).checked==false)
		notCheck = true;
	var valid = true;

	for ( var i = 0; i < requiredInQuotationInputs.length; i++) 
	{
		var pair = requiredInQuotationInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		if(notCheck==true)
		{
			input.css("background-color", normalColor);
			lbl.css("display", "none");
		}
		else
		{
			if (input.length && lbl.length)
			{
				if (input.val().trim() != '') {
					input.css("background-color", normalColor);
					lbl.css("display", "none");
					
				} else {
					input.css("background-color", warningColor);		
					lbl.css("display", "block");
					valid = false;
				}
			}
		}
	}
	if(notCheck==true)
		return true;
	else
		return valid;
}

function checkIntInputs(intInputs) {
	
	// Example:  var intInputs = [['id','id_invalid'],['object_id','object_id_invalid'],['status','status_invalid'],['notification','notification_invalid']];
	
	var valid = true;

	for ( var i = 0; i < intInputs.length; i++) {
		var pair = intInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		
		var value = input.val();
		
		var isInt = true;
		isInt=isInteger(value);

		if (isInt == false) {
			lbl.css("display", "block");
			valid = false;
		} else {
			lbl.css("display", "none");
		}
	}

	return valid;
}

function checkDoubleInputs(doubleInputs, decimalSep, thousandSep) {
	var valid = true;

	for ( var i = 0; i < doubleInputs.length; i++) {
		var pair = doubleInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		
		var value = input.val();
		
		var isNumeric = true;
		
		isNumeric=isNumerics(value,decimalSep,thousandSep);

		if (isNumeric == false) {
			lbl.css("display", "block");
			valid = false;
		} else {
			lbl.css("display", "none");
		}
	}

	return valid;
}

//This function used for checking correct date string input for some un-required fields.
//Note: the function returns "true" if date string is empty. 
function checkDateInputsForCorrectedFormatOnly(dateInputs, dateFormat) {
	var valid = true;
	for ( var i = 0; i < dateInputs.length; i++) {
		var pair = dateInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		
		var value = input.val();
		if (value.trim() == '')
		{
			//accept empty string case.
			continue;
		}
		var isDate = true;
		isDate = isDateString(value, dateFormat);	

		if (isDate == false) {
			input.css("background-color", warningColor);
			lbl.css("display", "block");
			valid=false;
		} else {
			input.css("background-color", normalColor);
			lbl.css("display", "none");
		}
	}
	return valid;	
}

function checkDateInputs(dateInputs, dateFormat) {
	var valid = true;
	for ( var i = 0; i < dateInputs.length; i++) {
		
		var pair = dateInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		
		var value = input.val();
		var isDate = true;			
		isDate = isDateString(value, dateFormat);	

		if (isDate == false) {
			input.css("background-color", warningColor);
			lbl.css("display", "block");
			valid=false;
		} else {
			input.css("background-color", normalColor);
			lbl.css("display", "none");
		}
	}
	return valid;
}

function checkTimeInputsForCorrectFormatOnly(timeInputs, timeFormat) {
	var valid = true;

	for (var i = 0; i < timeInputs.length; i++) {
		var pair = timeInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		
		var value = input.val();
		if (value.trim() == '')
		{
			continue;
		}	
		var isTime = true;
		isTime = isTimeString(value,timeFormat);
		
		if (isTime == false) {
			lbl.css("display", "block");
			input.css("background-color", warningColor);
			valid = false;
		} else {
			lbl.css("display", "none");
			input.css("background-color", normalColor);
		}
	}

	return valid;
}

function checkTimeInputs(timeInputs, timeFormat) {
	var valid = true;

	for ( var i = 0; i < timeInputs.length; i++) {
		var pair = timeInputs[i];

		var inputID = pair[0];
		var lblID = pair[1];

		var input = $('#' + inputID);
		var lbl = $('#' + lblID);
		
		var value = input.val();
		
		var isTime = true;
		isTime = isTimeString(value,timeFormat);
		
		if (isTime == false) {
			alert('not time');
			lbl.css("display", "block");
			input.css("background-color", warningColor);
			valid = false;
		} else {
			lbl.css("display", "none");
			input.css("background-color", normalColor);
		}
	}

	return valid;
}

function toggleControls(controlList) {
	for ( var i = 0; i < controlList.length; i++) {
		var id = controlList[i];
		var ctrl = $('#' + id);
		ctrl.toggle();
	}	
}

function isInteger(strString)
{
	var strValidChars = "0123456789";
	var strChar;
	
	if ((!strString) || strString.length == 0) return false;
	
	for (var i = 0; i < strString.length; i++)
	{
	   strChar = strString.charAt(i);
	   if(strString.length==1 && strChar == "-")
	   {
		   return false;
	   }
	   if(i == 0 && strChar == "-")
	   {
		   continue;
	   }
	   if (strValidChars.indexOf(strChar) == -1)
	   {
	      return false;
	   }
	}
	return true;
}

function isDateString(submitDate, dateFormat)
{
	
	var marker = dateFormat.charAt(2);
	
	//check for right format
	//TODO: fixed this for a general case
	var regex = /^[0-3]?[0-9]\/[0-1]?[0-9]\/\d{4}$/;
	if (!regex.test(submitDate))
	{
		return false;
	}
	
	if(submitDate.indexOf(marker) == -1)
	{
		return false;
	}

	var dateComp = submitDate.split(marker);
	if (dateComp.length != 3 )
	{
		return false;
	}
	
	for (var i=0; i < 3; i++)
	{
		if(isNaN(dateComp[i]))
		{
			return false;
		}	
	}

	var day = 0;
	var month = 0;
	var year = 0;
	
	if(dateFormat.charAt(0)=='m')
	{
		day = dateComp[1];
		month = dateComp[0];
	}
	else
	{
		day=dateComp[0];
		month=dateComp[1];
	}
	
	year=dateComp[2];

	if(year<1)
	{
		return false;
	}

	dayInmonth = new Array(12);

	dayInmonth[0]=31;

	dayInmonth[1]=29;

	dayInmonth[2]=31;

	dayInmonth[3]=30;

	dayInmonth[4]=31;

	dayInmonth[5]=30;

	dayInmonth[6]=31;

	dayInmonth[7]=31;

	dayInmonth[8]=30;

	dayInmonth[9]=31;

	dayInmonth[10]=30;

	dayInmonth[11]=31;

	if (month > 12 || month < 1)

	{
		return false;
	}

	if (year % 4 == 0)

	{
		dayInmonth[1]=29;
	}

	else

	{
		dayInmonth[1]=28;		
	}

	if (day > dayInmonth[month-1] || day < 1)

	{
		return false;
	}

	return true;

}

function isTimeString(submitTime, timeFormat)
{
	//check for right format
	//TODO: fixed this for a general case
	var regex = /^[0-3]?[0-9]\/[0-1]?[0-9]\/\d{4} at [0-2]?[0-9]:[0-5]?[0-9]$/;
	
	if (!regex.test(submitTime))
	{
		return false;
	}
	else
	{
		return true;
	}	
	
	//TODO: fix me
	var marker = ':';
	var markerIndex = submitTime.indexOf(marker);
	if(markerIndex == -1)
	{
		
		return false;
	}
	
	var h = submitTime.substring(0,markerIndex);
	var m = submitTime.substring(markerIndex+1);
	if(h == "" || h == " " || h=="  " || h=="   " || m=="" || m==" " || m=="  " || m=="   ")
	{
		return false;
	}
	var timeComp=submitTime.split(marker);
	if (timeComp.length != 2 )
	{
		return false;
	}
	
	for (var i=0; i < 2; i++)
	{
		if(isNaN(timeComp[i]))
		{
			return false;
		}
	}
	var hour=0;
	var minute=0;
	if(timeFormat.charAt(0)=='h')
	{
		hour=timeComp[0];
		minute=timeComp[1];
	}
	else
	{
		hour=timeComp[1];
		minute=timeComp[0];
	}
	if(hour > 23 || hour < 0)
	{
		return false;
	}
	if(minute > 59 || minute < 0)
	{
		return false;
	}
	return true;

}

function isNumerics(strString,descimalSep,thousandSep) 
{
	var strValidChars = "0123456789.,";
	var strChar;

	if (strString.length == 0) return false;
	var d=0;
	for (var i = 0; i < strString.length; i++)
	{
	   strChar = strString.charAt(i);
	   if(strString.length==1 && strChar == "-")
	   {
		   return false;
	   }
	   if(i == 0 && strChar == "-")
	   {
		   continue;
	   }
	   if (strValidChars.indexOf(strChar) == -1)
	   {
	      return false;
	   }
	   if(strChar==descimalSep)
	   {
		   if(d==0) d++;
		   else return false;
			   
	   }
	}
	var desSepIndex=strString.indexOf(descimalSep);
	var intPart=strString.substring(0,desSepIndex);
	var desPart=strString.substring(desSepIndex+1);
	if(desPart.indexOf(thousandSep)!=-1)
	{
		return false;
	}
	var k=0;
	for(var j=intPart.length;j>0;j--)
	{
		strChar = intPart.charAt(j-1);
		if(strChar==thousandSep && (k % 3)!=0)
		{
			return false;
		}
		k++;
	}
	return true;
}

function toggleHyjackControl(aSelectors)
{
	for ( var i = 0; i < aSelectors.length; i++) {
		var selector = '#' + aSelectors[i];
		var isDisabled = $(selector).attr('disabled');

		if (isDisabled == false) {
			$(selector).attr('disabled', 'disabled');
			$.hyjack_select.update(selector);
		}
		else {
			$(selector).removeAttr('disabled');
			$.hyjack_select.update(selector);
		}
	}	
}

function onlyNumberAllowed(evt) 
{
	var theEvent = evt || window.event;
	var key = theEvent.keyCode || theEvent.which;
	key = String.fromCharCode( key );
	var regex = /[0-9]|\./;
	if( !regex.test(key) ) 
	{
		theEvent.returnValue = false;
		if(theEvent.preventDefault) 
		{
			theEvent.preventDefault();
		}
	}
}

function turnOnNumbericInput()
{
	// global numeric: $(".numeric").numeric();
	$(".inputInt").numeric(false, function() { alert("Integers only"); this.value = ""; this.focus(); });
	$(".inputNumeric").numeric({ negative: false }, function() { alert("No negative values"); this.value = ""; this.focus(); });
	//$(".positive-integer").numeric({ decimal: false, negative: false }, function() { alert("Positive integers only"); this.value = ""; this.focus(); });		
}

// column toggling function
$.fn.toggleColumn = function(column){
    // Make sure column has value
    if(!column){
    	return this;
    }
    $('tr td:nth-child(' + column + '), tr th:nth-child(' + column + ')', this).toggle();
    return this;
};
// ////////////////////////////////////////////////////
function initDatePicker()
{
	$( ".inputDate" ).datepicker({
		numberOfMonths: 2,
		showButtonPanel: true,
		dateFormat: 'dd/mm/yy'
	});	
}

function initDateTimePicker()
{
	$('.inputDateTime').datetimepicker({
		dateFormat: 'dd/mm/yy',
		separator: ' at ',
		numberOfMonths: 2,
		hourGrid: 4,
		minuteGrid: 10
	});	
}

function validateDateTimeInput(txt, isRequired)
{
	var input = $('#' + txt);
	var dateString = input.val();
	if (dateString.trim() != '')
	{
		var requiredError = $('#' + txt + '_required');
		if (requiredError.length)
			requiredError.css("display", "none");
		if (!isTimeString(dateString, dateFormat))
		{
			$('#' + txt + '_invalid').css("display", "block");
			input.css("background-color", warningColor);
		}
		else
		{
			$('#' + txt + '_invalid').css("display", "none");
			input.css("background-color", normalColor);
		}
	}	
	// Dat added here
	else
	{
		if(!isRequired)
		{
			$('#' + txt + '_invalid').css("display", "none");
			input.css("background-color", normalColor);
		}
		else
		{
			$('#' + txt + '_invalid').css("display", "none");
			$('#' + txt + '_required').css("display", "block");
			input.css("background-color", warningColor);
		}
	}
}

function validateDateInput(txt,isRequired)
{
	var input = $('#' + txt);
	var dateString = input.val();
	if (dateString.trim() != '')
	{
		var requiredError = $('#' + txt + '_required');
		if (requiredError.length)
			requiredError.css("display", "none");
		if (!isDateString(dateString, dateFormat))
		{
			$('#' + txt + '_invalid').css("display", "block");
			input.css("background-color", warningColor);
		}
		else
		{
			$('#' + txt + '_invalid').css("display", "none");
			input.css("background-color", normalColor);
		}
	}	
	// Dat added here
	else
	{
		if(!isRequired)
		{
			$('#' + txt + '_invalid').css("display", "none");
			input.css("background-color", normalColor);
		}
		else
		{
			$('#' + txt + '_invalid').css("display", "none");
			$('#' + txt + '_required').css("display", "block");
			input.css("background-color", warningColor);
		}
	}
}

function validateRequiredInput(ctrl,haveTime)
{
	var input = $('#' + ctrl);
	var inputString = input.val();
	
	var color = input.css("background-color");
	//alert(color);
	if (inputString.trim() == '')
	{
		$('#' + ctrl + '_required').css("display", "block");
		input.css("background-color", warningColor);
	}
	else
	{
		$('#' + ctrl + '_required').css("display","none");
		// Dat modified here
		if(haveTime!=null)
		{
			if(!haveTime)
			{
				if(!isDateString(inputString, dateFormat))
					input.css("background-color", warningColor);
				else
					input.css("background-color", normalColor);
			}
			else
			{
				if(!isTimeString(inputString, dateFormat))
					input.css("background-color", warningColor);
				else
					input.css("background-color", normalColor);
			}
		}
		else
		{
			input.css("background-color", normalColor);
		}
	}
}



// ///////////////////////////////////////////////////
function initTooltip()
{
	$(".errMsg").tooltip({

		// /////place tooltip on the right edge
		position: "top left",

		// ////a little tweaking of the position
		offset: [-2, 10],

		// /////use the built-in fadeIn/fadeOut effect
		effect: "fade",

		// ////custom opacity setting
		opacity: 1.0,
		
		events: {
			def:     'mouseenter,mouseleave',    // default show/hide events for an element
			input:   'mouseenter, mouseleave blur mouseout focus',               // for all input elements
			widget:  'focus mouseenter, blur mouseleave mouseout',  // select, checkbox, radio, button
			tooltip: 'mouseenter,mouseleave'     // the tooltip element
		}

	});
	
	$(".inputInt, .inputText, .inputTextarea, .inputDate, .dropdownlistStyle, .btnAdd, .inputNumeric, .inputCheckbox, .inputDateTime").tooltip({

		// /////place tooltip on the right edge
		position: "center right",

		// ////a little tweaking of the position
		offset: [-2, 10],

		// /////use the built-in fadeIn/fadeOut effect
		effect: "fade",

		// ////custom opacity setting
		opacity: 1.0,
		
		events: {
			def:     'mouseenter,mouseleave',    // default show/hide events for an element
			input:   'mouseenter, mouseleave blur mouseout focus',               // for all input elements
			widget:  'focus mouseenter, blur mouseleave mouseout',  // select, checkbox, radio, button
			tooltip: 'mouseenter,mouseleave'     // the tooltip element
		}

	});
	
	$(".btnSubmit, .btnReset").tooltip({

		// /////place tooltip on the right edge
		position: "bottom center",

		// ////a little tweaking of the position
		offset: [10, 10],

		// /////use the built-in fadeIn/fadeOut effect
		effect: "fade",

		// ////custom opacity setting
		opacity: 1.0,
		
		events: {
			def:     'mouseenter,mouseleave',    // default show/hide events for an element
			input:   'mouseenter,mouseleave blur',               // for all input elements
			//widget:  'focus mouseenter, blur mouseleave mouseout',  // select, checkbox, radio, button
			tooltip: 'mouseenter,mouseleave'     // the tooltip element
		}

	});
	
}
// ////////////////////////////////////////
var KEY_TAB = 9;
var KEY_LEFT = 37;
var KEY_RIGHT = 39;
var KEY_BACKSPACE = 8;
var KEY_DELETE = 46;
var KEY_SHIFT = 16;
var KEY_CTRL = 16;
var KEY_PLUS = 107;
var KEY_EQUAL = 187;


function checkForControlKeyPress(key)
{
	if (key == KEY_LEFT || key == KEY_RIGHT || key == KEY_BACKSPACE || key == KEY_DELETE 
			|| key == KEY_CTRL || key == KEY_PLUS || key == KEY_EQUAL || key == KEY_TAB)
	{
		return true;
	}
	return false;
}

function phoneNumberTextKeyDown(evt, textbox)
{	
	var theEvent = evt || window.event;		
	var key = theEvent.keyCode || theEvent.which;
	var isCtrlKey = checkForControlKeyPress(key);
	
	key = String.fromCharCode(key);
	var regex = /[0-9]/;
	if(!regex.test(key) && !isCtrlKey)// isCtrlKey: is used for checking '+'
	{
		theEvent.returnValue = false;
		if(theEvent.preventDefault) 
		{
			theEvent.preventDefault();
		}
	}
}

function phoneNumberTextKeyUp(textbox) {
	var str = textbox.value; // document.getElementById(ele).value;
	var validChar = "0123456789";
	var leng = str.length;
	var ch;
	var invalidIndex = -1;

	for(var i = 0; i < leng; i++)
	{
		ch = str.charAt(i);

		if(ch == '+' && i == 0)
		{
			continue;
		}
		
		if(validChar.indexOf(ch)== -1)
		{
			invalidIndex=i;
			break;
		}
	}
	if(invalidIndex > -1)
	{
		str = str.substring(0, invalidIndex);
	}
	textbox.value = str;
	// document.getElementById(ele).value = str;
}
// /////////////////////////////////////////
// Confirm delete confirmation dialog
function initDeleteConfirmation()
{
	$('body').append("<div id='dialog-confirm' title='Delete confirmation dialog'></div>");
 	$(".hrefDelete").click(function() {
		var id = $(this).attr("id");
		var parent = $(this).closest('tr');
		var link = this.href;
		var confirmTitle = this.title;
		if (!confirmTitle){
			confirmTitle = "Do you want to delete it now?";
		}
		
		$('#dialog-confirm').dialog({
						resizable: false,
						height:140,
						width: 300,
						modal: true,
						title: confirmTitle,
						buttons: {
							'Delete ?': function() {
								$(this).dialog('close');
								if (link)
								{
									window.location.href = link;
								}
								else
								{
									alert('plz add href for this');
									// TODO: do some thing.
								}
								return true;
							},
							Cancel: function() {
							   $(this).dialog('close');
							   return false;
							}
						}
					});
				return false;
	});
}

function confirmToDelete()
{
	$('#dialog-confirm').dialog('open');	
}
// End of delete confirmation dialog

